
/**    
 *   This file is part of the FSKModem java/android library for 
 *   processing FSK audio signals. 
 *   
 *   The FSKModem library is developed by Ivan Ganev, CEO at
 *   Cytec BG Ltd.
 *
 *   Copyright (C) 2014  Cytec BG Ltd. office@cytec.bg
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package bg.cytec.android.fskmodem;

import java.io.IOException;
import java.nio.ShortBuffer;

import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import bg.cytec.android.fskmodem.FSKEncoderVar.FSKEncoderCallback;

public class EncodeLive8bitFreyActivity extends Activity {

	public static final String ENCODER_DATA = "Hello World! This text has been encoded realtime and then fed to audio playback stream and the FSK decoder that actually displays it.";
	
	protected FSKConfig mConfig;
	protected FSKEncoderVar mEncoder;
	protected FSKDecoder mDecoder;
	
	protected AudioTrack mAudioTrack;
	
	private short[] data = null;
	
	private EditText editText;
	
	private EditText frey;
	
    public int pwMinBufferSize = 0;
	
	protected Runnable mDataFeeder = new Runnable() {
		
		@Override
		public void run() {
//			byte[] data = ENCODER_DATA.getBytes();
			
			if (data.length > FSKConfig.ENCODER_DATA_BUFFER_SIZE) {
				//chunk data
				short[] buffer = new short[FSKConfig.ENCODER_DATA_BUFFER_SIZE];
				ShortBuffer dataFeed = ShortBuffer.wrap(data);
				while (dataFeed.remaining() > 0) {
					
					if (dataFeed.remaining() < buffer.length) {
						buffer = new short[dataFeed.remaining()];
					}
					
					dataFeed.get(buffer);
					mEncoder.appendData(buffer);
					try {
						Thread.sleep(100); //wait for encoder to do its job, to avoid buffer overflow and data rejection
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
			else {
				mEncoder.appendData(data);
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_frey);
		editText = (EditText)findViewById(R.id.fsmText);
		frey = (EditText)findViewById(R.id.frey);
		///
	}
	
	@Override
	protected void onDestroy() {
		stop();
		super.onDestroy();
	}

	
	public void onClick(View view){
		switch (view.getId()) {
		case R.id.play:
			int freg = Integer.parseInt(frey.getText().toString());
			/// INIT FSK CONFIG
			try {
				pwMinBufferSize = AudioTrack.getMinBufferSize(freg,  AudioFormat.CHANNEL_OUT_STEREO,   AudioFormat.ENCODING_PCM_8BIT);
				mConfig = new FSKConfig(FSKConfig.SAMPLE_RATE_44100, FSKConfig.PCM_8BIT, FSKConfig.CHANNELS_STEREO, FSKConfig.SOFT_MODEM_MODE_6, FSKConfig.THRESHOLD_20P);
				mConfig.setFrey(freg);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			/// INIT FSK ENCODER
			mEncoder = new FSKEncoderVar(mConfig, new FSKEncoderCallback() {
				@Override
				public void encoded(byte[] pcm8, short[] pcm16) {
					if (mConfig.pcmFormat == FSKConfig.PCM_8BIT) {
						//8bit buffer is populated, 16bit buffer is null
						mAudioTrack.write(pcm8, 0, pcm8.length);
							//mDecoder.appendSignal(pcm8);
					}
					else if (mConfig.pcmFormat == FSKConfig.PCM_16BIT) {
						//16bit buffer is populated, 8bit buffer is null
						
						mAudioTrack.write(pcm16, 0, pcm16.length);
						
						mDecoder.appendSignal(pcm16);
					}
				}
			});
			
			///
			mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
					mConfig.sampleRate, AudioFormat.CHANNEL_OUT_STEREO,
					AudioFormat.ENCODING_PCM_8BIT, pwMinBufferSize,
					AudioTrack.MODE_STREAM);
			mAudioTrack.play();
			String cmds = editText.getText().toString();
			data =  String2Int(cmds);
			new Thread(mDataFeeder).start();
			break;
		case R.id.stop:
			stop();
			break;
		default:
			break;
		}
	}

	private void stop(){
		if(mDecoder != null){
			mDecoder.stop();
		}
		if(mEncoder != null){
			mEncoder.stop();
		}
		if(mAudioTrack != null){
			mAudioTrack.stop();
			mAudioTrack.release();
		}
	}
	
	public static short[] String2Int(String _s) {
		String s[] = _s.split(",");
		int iLen = s.length;
		short aCMD[] = new short[iLen];
		for (int i = 0; i < s.length; i++) {
			aCMD[i] = CInt(s[i], (short)0);
		}
		return aCMD;
	}
	
	/*
	 * 字符串转为整数 str 源字符串, default 默认值
	 */
	public static short CInt(String str, short iDefault) {
		short iR = iDefault;
		try {
			iR = Short.parseShort(str);
		} catch (NumberFormatException e) {
			iR = iDefault;
		}
		return iR;
	}
	
}

